package com.myway.utils.htmltopdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.font.FontProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * html转pdf
 */
public class HtmlToPdfUtil {

    public static void main(String[] args) throws Exception {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String outputFile= request.getSession().getServletContext().getRealPath("/WEB-INF/files/test.pdf");

        //String outputFile = "d:/test.pdf";
        String inputFile = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<body>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n" +
                "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n" +
                "<title></title>\n" +
                "<style type=\"text/css\">\n" +
                "body {margin: 0;padding: 0;font-family: \"Hiragino Sans GB\", \"Microsoft YaHei\", \"WenQuanYi Micro Hei\", sans-serif;font-size: 14px;text-align: center;}\n" +
                "</style>\n" +
                "<div style=\"width:80%;text-align:left;margin: 0 auto;\">\n" +
                "    <p>\n" +
                "\t  <table style=\"width:100%;\">\n" +
                "\t    <tr>\n" +
                "\t\t  <td><img src=\"\" width=\"150px\" height=\"100px;\"/></td>\n" +
                "\t\t  <td style=\"width:50%;text-align:left;\">\n" +
                "\t\t    <h3>ITINERARY</h3>\n" +
                "\t\t  </td>\n" +
                "\t\t</tr>\n" +
                "\t  </table>\n" +
                "\t</p>\n" +
                "    <p>\n" +
                "       <span style=\"background:#D3D3D3;\">&nbsp;&nbsp;Booking Details&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n" +
                "       ----------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
                "\t   <br/><br/>\n" +
                "\t   <table>\n" +
                "\t     <tr>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Order ID：</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;width:40%;\">7478478693</td>\n" +
                "\t\t </tr>\n" +
                "\t\t <tr>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Passenger：</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;width:40%;\">ZHAO/JIUFENG</td>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Issue Date：</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;\">25OCT 2018</td>\n" +
                "\t\t </tr>\n" +
                "\t\t <tr>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Ticket Number：</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;width:40%;\">784-2876609148</td>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">PNR:</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;\">JN8E5Y</td>\n" +
                "\t\t </tr>\n" +
                "\t\t <tr>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Issuing Airline:</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;width:40%;\">Myway Airlines</td>\n" +
                "\t\t   <th align=\"left\" style=\"padding-left:5px;padding-top:2px;\">Issued Agent：</th>\n" +
                "\t\t   <td align=\"left\" style=\"padding-left:5px;padding-top:2px;\">PEK989</td>\n" +
                "\t\t </tr>\n" +
                "\t   </table>\n" +
                "\t   <br/><br/>\n" +
                "\t</p>\n" +
                "\t<p>\n" +
                "\t   <span style=\"background:#D3D3D3;\">&nbsp;&nbsp;Flight Details&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n" +
                "\t   ----------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
                "\t   <br/><br/>\n" +
                "\t   <table border=\"1\" style=\"border-collapse:collapse;margin: 0 auto;padding: 0;font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 'WenQuanYi Micro Hei', sans-serif;font-size: 14px;text-align: left;width:100%;\">\n" +
                "\t      <tr>\n" +
                "\t\t    <th align=\"center\" style=\"padding:0px;margin:0px;\">Date</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">Airline PNR</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">Flight</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">Departure Time<br/>\n" +
                "                Terminal\n" +
                "\t\t\t</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">\n" +
                "\t\t\t    Arrival Time<br/>\n" +
                "                Terminal\n" +
                "\t\t\t</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">Class</th>\n" +
                "\t\t\t<th align=\"center\" style=\"padding:0px;margin:0px;\">Status</th>\n" +
                "\t\t  </tr>\n" +
                "\t\t  <tr>\n" +
                "\t\t    <td align=\"center\">25-OCT-18</td>\n" +
                "\t\t\t<td align=\"center\">MT9JVR</td>\n" +
                "\t\t\t<td align=\"center\">MJ201</td>\n" +
                "\t\t\t<td align=\"center\">TBS-Tbilisi 14:40 TERMINAL 2</td>\n" +
                "\t\t\t<td align=\"center\">FCO-Rome 21:30 TERMINAL 1</td>\n" +
                "\t\t\t<td align=\"center\">Economy</td>\n" +
                "\t\t\t<td align=\"center\">OK</td>\n" +
                "\t\t  </tr>\n" +
                "\t   </table>\n" +
                "\t   <br/><br/>\n" +
                "\t</p>\n" +
                "\t<p>\n" +
                "\t   <span style=\"background:#D3D3D3;\">&nbsp;&nbsp;Payment Details&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n" +
                "\t   ----------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
                "\t   <br/><br/>\n" +
                "\t   <table>\n" +
                "\t      <tr>\n" +
                "\t\t    <th>Fare：</th>\n" +
                "\t\t\t<td>USD124.00</td>\n" +
                "\t\t  </tr>\n" +
                "\t\t  <tr>\n" +
                "\t\t    <th>Tax：</th>\n" +
                "\t\t\t<td>USD124.00</td>\n" +
                "\t\t  </tr>\n" +
                "\t\t  <tr>\n" +
                "\t\t    <th>Total：</th>\n" +
                "\t\t\t<td>USD124.00</td>\n" +
                "\t\t  </tr>\n" +
                "\t   </table>\n" +
                "\t   <br/><br/>\n" +
                "\t</p>\n" +
                "\t<p>\n" +
                "\t   <span style=\"background:#D3D3D3;\">&nbsp;&nbsp;Notice&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>\n" +
                "\t   ----------------------------------------------------------------------------------------------------------------------------------------------------------\n" +
                "\t   <br/><br/>\n" +
                "\t   <span>\n" +
                "\t\t• An electronic ticket has been issued for you. To receive a boarding pass please use check-in counters at the airport of departure. For identification please have your booking reference or the credit card which has been used at the time of booking ready.<br/>\n" +
                "\t\t•We recommend to arrive at the airport 2 hours before departure for check-in.<br/>\n" +
                "\t\t• Please take note of the current free baggage allowance included in your ticket price and the applicable hand baggage regulations prior to your departure. If you are planning to take excess or special baggage with you, different conditions may apply.Please be advised that due to security reasons items which are classified as dangerous goods are prohibited on board.<br/>\n" +
                "\t\t• Myway Airlines flight bookings do not require a reconfirmation after ticket purchase.<br/>\n" +
                "\t\t• Please check the applicable visa and health entry requirements. Myway Airlines requires its passengers to have a valid passport and visa (if applicable) whilst traveling.<br/>\n" +
                "\t\t• Passenger Notice - (link to website page)\n" +
                "\t   </span>\n" +
                "\t</p>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        System.out.println(htmlToPdf(inputFile,outputFile));
    }

    /**
     * @desc html转换成pdf
     * @param htmlContent ： 要生成pdf的html内容
     * @param outputFilePath ：文件输出路径
     * @return
     */
    public static boolean htmlToPdf(String htmlContent,String outputFilePath){
        try {
            WriterProperties writerProperties = new WriterProperties();
            //Add metadata
            writerProperties.addXmpMetadata();
            FileOutputStream fos = new FileOutputStream(outputFilePath);//outputFile为生成存放的路径如：d:/test.pdf
            PdfWriter pdfWriter = new PdfWriter(fos, writerProperties);

            PdfDocument pdfDoc = new PdfDocument(pdfWriter);
            pdfDoc.getCatalog().setLang(new PdfString("UTF-8"));
            //Set the document to be tagged
            pdfDoc.setTagged();
            pdfDoc.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));

            //Set meta tags
            PdfDocumentInfo pdfMetaData = pdfDoc.getDocumentInfo();
            pdfMetaData.setAuthor("XX");
            pdfMetaData.addCreationDate();
            pdfMetaData.getProducer();
            pdfMetaData.setCreator("XXX");
            pdfMetaData.setKeywords("resume");
            pdfMetaData.setSubject("PDF resume");

            // pdf conversion
            ConverterProperties props = new ConverterProperties();
            FontProvider fp = new FontProvider();
            fp.addStandardPdfFonts();
            fp.addDirectory(outputFilePath);//The noto-nashk font file (.ttf extension) is placed in the resources
            fp.addSystemFonts();
            props.setFontProvider(fp);
            props.setBaseUri(outputFilePath);

            //inputFile是要转化的内容
            HtmlConverter.convertToPdf(new ByteArrayInputStream(htmlContent.getBytes("utf-8")), pdfDoc, props);
            pdfDoc.close();

            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @desc  邮件附件html内容
     * @param map：动态参数
     * @return
     */
    public static String returnHtmlContent(Map<String,String> map){
        String logoUrl = StringUtils.isEmpty(map.get("logoUrl"))?"http://47.75.92.162:48061/img/newlogo.png":map.get("logoUrl");
        String company = map.get("company");
        String invoiceNumber = map.get("invoiceNumber");
        String address = map.get("address");
        String pnr = map.get("pnr");
        String vat = map.get("vat");
        String bookingDate = map.get("bookingDate");
        String ticketNumber = map.get("ticketNumber");
        String name = map.get("name");
        String param1 = map.get("param1");
        String param2 = map.get("param2");
        String param3 = map.get("param3");
        String param4 = map.get("param4");
        String fare = map.get("fare");
        String taxes = map.get("taxes");
        String total = map.get("total");
        String invoiceDateUtc = map.get("invoiceDateUtc");

        //退改签规则
        String rebookrule = map.get("rebookrule");

        StringBuffer sbf = new StringBuffer();
        sbf.append("<html lang=\"zh-CN\"><head><meta charset=\"utf-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"><title>MYWAY AIRLINES</title>")
            .append("<style>body{ font-family: -apple-system, BlinkMacSystemFont, 'Microsoft YaHei', sans-serif;font-size: 16px;color: #333;line-height: 1.75;}p{margin: 0;}")
            .append(".nav_logo{display:inline-block;width:232px;height:120px;background:url(\"")
            .append(logoUrl)
            .append("\")  center no-repeat;background-size:100%100%;}")
            .append(".line{width:100%;height: 1px;background: #1b6d85;} .bold{height: 2px;} .mt30{margin-top: 30px;} .mt50{margin-top: 50px;} .col-primary{color:#337ab7;}")
            .append(".btn {display: inline-block;padding: 6px 12px;margin-bottom: 0; font-size: 14px;font-weight: 400;line-height: 1.42857143;text-align: center;vertical-align: middle; cursor: pointer; ")
            .append("background-image: none;border: 1px solid #2e6da4; color: #fff;background-color: #337ab7; }")
            .append(".container {width: auto; margin:0 60px 0 60px;} .col-4{width: 50%;} .col-8 {width: 50%;text-align: right;} .col-4,.col-8{float:left;}</style>")
            .append("<body><div class=\"container\"><div style=\"min-height: 120px;\"><div class=\"h_logoBox pull-left\" style=\"position:absolute;\"><a style=\"display: block;\"><div class=\"nav_logo\"></div></a></div></div><main>")
                .append("<!-- 第1部分 -->")
            .append("<div><button class=\"btn\">INVOICE</button><p class=\"line\"></p><div style=\"overflow: hidden;\" class=\"mt30 clearfix\"><div class=\"col-4\"><span>Company:</span>")
            .append(company)
            .append("</div><div class=\"col-8\"><span>Invoice Number：</span>")
            .append(invoiceNumber)
            .append("</div><div class=\"col-4\"><span>Address：</span>")
            .append(address)
            .append("</div><div class=\"col-8\"><span>PNR：</span>")
            .append(pnr)
            .append("</div><div class=\"col-8\"><span>VAT：</span>")
            .append(vat)
            .append("</div><div class=\"col-8\"><span>Booking Date：</span>")
            .append(bookingDate)
            .append("</div></div></div>")
                .append("<!-- 第2部分 -->")
             .append("<div class=\"mt50\"><button class=\"btn\">Passengers</button><p class=\"line\"></p><table style=\"border-collapse:collapse;width: 100%;\" class=\"mt50\"><tr><td>passengers</td><td>")
             .append("Ticket Number")
             .append("</td></tr>")
             .append(name)
            /* .append("</td><td>")
             .append(ticketNumber)*/
             .append("</table><p class=\"line\"></p>")

                .append("<!--第3部分-->")
              .append("<div class=\"mt50\"><button class=\"btn\">Itinerary and fare</button><p class=\"line\"></p>")
              .append("<table style=\"border-collapse:collapse;width: 100%;\" class=\"table mt30\"><thead style=\"border-bottom: 1px solid #ddd;\">")
              .append(param1)
              .append("</thead>")
              .append("<tbody><tr style=\"border-bottom: 1px dashed #ddd\"><td class=\"col-primary\" colspan=\"4\" style=\"padding:10px 10px 5px;\">Adult/-s</td></tr>")
              .append("<tr style=\"border-bottom: 1px dashed #ddd\"><td style=\"text-align: left;padding:5px 10px;\">Fare</td><td colspan=\"4\" style=\"text-align: right;padding:5px 10px;\">")
              .append(fare)
              .append("</td></tr><tr style=\"border-bottom: 1px dashed #ddd\"><td style=\"text-align: left;padding:5px 10px;\">Taxes</td><td colspan=\"4\" style=\"text-align: right;padding:5px 10px;\">")
              .append(taxes)
              .append("</td></tr><tr style=\"border-bottom: 1px dashed #ddd\" class=\"col-primary\"><td style=\"text-align: left;padding:5px 10px;\">Total</td> <td colspan=\"4\" style=\"text-align: right;padding:5px 10px;\">")
              .append(total)
              .append("</td></tr></tbody></table></div><p class=\"line bold mt30\"></p>")


              .append("<!--第4部分-->")
              .append("<div class=\"mt50\" style=\"\"><button class=\"btn\">refund/change rules</button><p class=\"line\"></p><div class=\"mt30\"><p>")
              .append(rebookrule)
              .append("</p></div></div></main>")

                  .append("<!--底部footer-->")
              .append("<div style=\"margin-top: 30px;text-align: center;\"><p class=\"col-primary\">This is an informative invoice and is not subject to payment.</p>Invoice dispatched on: ")
              .append(invoiceDateUtc)
              .append(" (UTC)</div></div></body></html>");
        return sbf.toString();
    }

    /**
     * @desc 获取当前日期格式数据： yyyyMMddHHmm
     * @return
     */
    public static String returnToday(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        return sdf.format(new Date());
    }

}